<template>
	<view v-if="Detail!=null">
		<cu-custom bgColor="theme-bg-color fixed" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content"><text>{{Detail.Name}}</text></block>
		</cu-custom>
		
		<!-- 地图部分保持不变 -->
		<view class="page-body">
			<view class="page-section page-section-gap">
				<map id="map" scale='20' style="width: 100%; height: 100vh;" enable-zoom="true" enable-traffic="true"
					:latitude="location.latitude" :longitude="location.longitude" :circles="circles"
					:polyline="polyline" :markers="markers">
				</map>
			</view>
		</view>
		
		<!-- 拍照界面（初始隐藏） -->
		<view class="camera-container" v-if="showCamera">
			<camera 
				id="camera" 
				device-position="front" 
				flash="off" 
				style="width: 100%; height: 100vh;"
				@error="onCameraError">
			</camera>
			
			<view class="camera-buttons">
				<button class="btn-capture" @click="takePhoto">拍照打卡</button>
				<button class="btn-cancel" @click="cancelPhoto">取消</button>
			</view>
		</view>
		
		<!-- 底部打卡按钮 -->
		<view class="fixed-bottom" v-if="!showCamera">
			<view class="flex ">
				<view v-if='isAllowCricle==false'><text
						class='text-bold text-lg text-red'>你不在可打卡的范围,距离{{distance}}米</text></view>
			</view>
			<view class="flex  margin-top-xs align-center justify-center " v-if="ClockInfo!=null">
				<view v-if='ClockInfo.CheckCount==2'>
					<view class="click-item  bg-green ">
						<text class="text-bold tex-lg">今天已经完成打卡!</text>
					</view>
					<text v-if="ClockInfo.IsCheckTime==null" class="text-red text-sm margin-top-xs">注:不在正常打卡时间内</text>
				</view>
				<view v-if='ClockInfo.CheckCount==0' @click="showCamera = true">
					<view class="click-item " :class="isAllowCricle==false?'bg-gray text-black':'bg-blue' ">
						<text class="text-bold tex-lg" :class="isAllowCricle==false?' text-black':'text-white' "
							:disabled="isAllowCricle">上课卡</text>
					</view>
					<text v-if="ClockInfo.IsCheckTime==null" class="text-red text-sm margin-top-xs">注:不在正常打卡时间内</text>
				</view>
				<view v-if='ClockInfo.CheckCount==1' @click="showCamera = true">
					<view class="click-item " :class="isAllowCricle==false?'bg-gray ':'bg-blue' ">
						<text class="text-bold tex-lg"
							:class="isAllowCricle==false?' text-black':'text-white' ">下课卡</text>
					</view>
					<text v-if="ClockInfo.IsCheckTime==null" class="text-red text-sm margin-top-xs">注:不在正常打卡时间内</text>
				</view>
			</view>
		</view>
	</view>
</template>


<script>
	import store from "@/store";
	import BigNumber from '@/utils/bignumber.js'
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				showCamera: false, // 控制摄像头显示
				Detail: null,
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				polyline: [{
					points: [],
					color: '#FF0000AA', // 多边形颜色
					width: 10, // 多边形宽度
					dottedLine: true // 是否为虚线
				}],
				polygon: [{
					strokeWidth: "2",
					strokeColor: "#FF0000AA",
					fillColor: '#FF0000AA', // 多边形颜色
				}],
				allLines: [],
				circles: [],
				markers: [],
				stop: false,
				isAllowCricle: false,
				time: 0,
				distance: 0,
				ClockInfo: null,
				CheckSettingId: 0
			}
		},
		computed: {
			...mapGetters(["userInfo", "userId", "location"]),
		},
		onLoad(option) {
			// 打印请求参数CheckSettingId
			console.log("CheckSettingId", option.checkSettingId);
			this.CheckSettingId = option.checkSettingId;
		},
		onShow() {
			this.GetOrganizationApi();
		},
		onHide() {
			clearInterval(this.time);
		},
		onUnload() {
			clearInterval(this.time);
		},
		onReady() {

			this._mapContext = uni.createMapContext("map", this);
			this.GetMyLocation();
		},
		methods: {
			//定时同步我的状态
			async TimingSyncStatus() {
				this.time = setInterval(() => {
					this.SyncStatus();
				}, 5000)
			},
			//同步我的位置状态
			async SyncStatus() {
				this.GetMyLocation();
				let currentDistance = this.getGreatCircleDistance(this.Detail.Latitude, this.Detail
					.Longitude, this
					.location.latitude, this.location.longitude);
				console.log(currentDistance, this.Detail.Distance);
				this.distance = currentDistance - this.Detail.Distance;
				this.isAllowCricle = currentDistance < this.Detail.Distance;
				console.log("当前距离边缘", this.distance, '中心', currentDistance, this.isAllowCricle)

			},
			//得到打卡状态
			async GetClockInfoApi() {
				let {
					Data
				} = await this.$http.PostAsync("/CheckRecord/GetClockInfo", {
					OrganizationId: this.userInfo.OrganizationId,
					UserId: this.userInfo.Id
				});
				this.ClockInfo = Data;

			},
			//进行打卡
			async Clock() {
				// if (this.isAllowCricle == false) {
				// 	await this.$comm.ShowToast("你不在可打卡的范围");
				// 	return;
				// }
				if (this.ClockInfo.IsCheckTime == null) {
					let confirm = await this.$comm.ShowModal("不在正常时间打卡你确定要打卡吗?");
					if (confirm != true) {
						return;
					}
				}
				//跳转到人脸识别
				console.log("okpp")
				console.log("跳转到人脸识别")
				// return
				// uni.navigateTo({
				// 	url: "/pages/user-center/UpdateFace",
				// 	events: {
				// 		data: async (path) => {

				// 			let bs64 = await this.$comm.TempToBase64(path);
				// 			await this.SumbitClock(bs64.data, path)

				// 		}
				// 	}
				// })
				
				this.uploadImage();

			},
			
			async TempToBase64(tempFiles) {
					// #ifdef H5
						
					return new Promise((resolve, reject) => {
						const reader = new FileReader();
						// 如果 tempFiles 是 File 对象
						if (tempFiles instanceof File) {
							reader.readAsDataURL(tempFiles);
						}
						// 如果 tempFiles 是 URL 字符串
						else {
							fetch(tempFiles)
								.then(response => response.blob())
								.then(blob => reader.readAsDataURL(blob))
								.catch(err => reject(err));
						}
						
						reader.onload = () => {
							const base64 = reader.result.split(',')[1];
							resolve({ data: base64 });
						};
						reader.onerror = error => reject(error);
					});
						
					// #endif
					// #ifdef MP-WEIXIN || MP-QQ
					// 非 H5 平台使用原有逻辑
					return new Promise((resolve, reject) => {
						uni.getFileSystemManager().readFile({
							filePath: tempFiles,
							encoding: 'base64',
							success(dataRes) {
								resolve(dataRes);
							},
							fail(err) {
								reject(err);
								console.error('读取文件失败：' + err.message);
							}
						});
					});
					// #endif
				},
				async uploadImage() {
					uni.chooseImage({
						count: 1,
						success: async (res) => {
							const tempFilePath = res.tempFilePaths[0];
							let bs64 = await this.TempToBase64(tempFilePath);
							console.log(bs64)
							await this.SumbitClock(bs64.data,tempFilePath)
						
						}
					});
				},
				
				
			//打卡提交
			async SumbitClock(base64, path) {
				try {
					let {
						Data,

					} = await this.$http.PostAsync("/Face/FaceSearch", {
						UserId: this.userInfo.Id,
						Image: base64
					});
					console.log(Data);
					console.log(JSON.parse(Data))
					let result = JSON.parse(Data);
					if (result.error_msg != "SUCCESS" || result.result.face_num == 0) {
						await this.$comm.ShowToast("没有识别的正确有效的人脸");
						return;
					}
					var userIds =[]
					result.result.face_list.forEach((item)=>{
						item.user_list.forEach((userItem)=>{
							userIds.push(userItem.user_id);
						})
					})
					console.log(userIds)
					console.log(userIds.filter(x=>x==this.userInfo.Id).length==0)
					if(userIds.filter(x=>x==this.userInfo.Id).length==0)
					{
						await this.$comm.ShowToast("没有识别的正确有效的人脸");
						return;
					}

					let {
						Data: ImageUrls
					} = await this.$http.Upload(path);
					let imgUrl = ImageUrls[0].Url;

					let {
						Success,
						Message
					} = await this.$http.PostAsync("/CheckRecord/Check", {
						UserId: this.userInfo.Id,
						OrganizationId: this.userInfo.OrganizationId,
						Latitude: this.location.latitude,
						Longitude: this.location.longitude,
						FaceImageUrl: imgUrl,
						CheckSettingId: this.CheckSettingId,
						CheckType: "face"
					});
					if (Success) {
						this.$comm.showToast("打卡成功!");
						uni.navigateBack();
					} else {
						uni.hideLoading();
					}
				} catch {
				} finally {
					
					this.GetClockInfoApi();

				}

			},
			// 拍照方法
			takePhoto() {
				const cameraContext = uni.createCameraContext(this);
				cameraContext.takePhoto({
					quality: 'high',
					success: async (res) => {
						this.photoPath = res.tempImagePath;
						this.showCamera = false;
						
						// 处理照片并打卡
						// uni.showLoading({ title: '人脸识别中...' });
						try {
							let bs64 = await this.TempToBase64(this.photoPath);
							await this.SumbitClock(bs64.data, this.photoPath);
							uni.showToast({
								title: '打卡成功',
								icon: 'none'
							});
						} catch (error) {
							console.error('打卡失败:', error);
							uni.hideLoading();
							uni.showToast({
								title: '打卡失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.log('拍照失败', err);
						uni.showToast({
							title: '拍照失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 取消拍照
			cancelPhoto() {
				this.showCamera = false;
			},
			
			// 摄像头错误回调
			onCameraError(e) {
				console.log('摄像头错误:', e.detail);
				uni.showToast({
					title: '摄像头错误',
					icon: 'none'
				});
				this.showCamera = false;
			},
			//得到班级信息
			async GetOrganizationApi() {
				let {
					Data
				} = await this.$http.PostAsync("/Organization/Get", {
					Id: this.userInfo.OrganizationId
				});
				this.Detail = Data;

				let Distance = this.Detail.Distance > 0 ? this.Detail.Distance : 500;

				this.circles = [{
					latitude: this.Detail.Latitude,
					longitude: this.Detail.Longitude,
					radius: Distance,
					fillColor: "#00aa00aa"
				}];
				await this.SyncStatus();
				await this.TimingSyncStatus();
				await this.GetClockInfoApi();


			},
			//得到我的位置GPS
			GetMyLocation() {
				let covers = [];
				covers.push({
					latitude: this.location.latitude,
					longitude: this.location.longitude,
					iconPath: this.userInfo.ImageUrls,
					width: "20",
					height: "20",
					title: "您的位置",
					label: "" + this.userInfo.Name,
				})
				this.markers = covers;


			},
			getRad(d) {
				return d * Math.PI / 180.0;
			},
			getGreatCircleDistance(lat1, lng1, lat2, lng2) {
				var EARTH_RADIUS = 6378137.0;
				var PI = Math.PI;
				var radLat1 = this.getRad(lat1);
				var radLat2 = this.getRad(lat2);

				var a = radLat1 - radLat2;
				var b = this.getRad(lng1) - this.getRad(lng2);

				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
					.pow(Math.sin(b / 2), 2)));
				s = s * EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000.0;

				return s; // 公里数
			},
			// 生成圆形多边形的顶点坐标
			// 圆心坐标、半径(km)和边数
			GenerateCirclePoints: function(latitude, longitude, radius, sides) {
				const points = []; // 存储顶点坐标的数组
				const step = (2 * Math.PI) / sides; // 计算每个顶点之间的角度差

				for (let i = 0; i < sides; i++) {
					const angle = step * i; // 计算当前顶点的角度
					const lat = new BigNumber(latitude).plus(new BigNumber(radius).times(new BigNumber(Math.sin(
						angle))).dividedBy(new BigNumber(111.32))); // 计算当前顶点的纬度
					const lng = new BigNumber(longitude).plus(new BigNumber(radius).times(new BigNumber(Math.cos(
						angle))).dividedBy(new BigNumber(111.32).times(new BigNumber(Math.cos(
						new BigNumber(
							latitude).times(new BigNumber(Math.PI).dividedBy(new BigNumber(
							180)))))))).toFixed(
						14); // 计算当前顶点的经度
					points.push({
						latitude: lat.toFixed(14),
						longitude: lng
					}); // 将当前顶点的坐标存入数组中
				}

				return points; // 返回顶点坐标数组
			}

		}
	}
</script>
<style>
	.fixed-bottom {
		position: fixed;
		width: 100%;

		padding: 20upx;
		bottom: 0;
		left: 0;
		z-index: 9999;
		background-color: white;
	}

	.cur {
		background-color: #0065B7 !important;
		color: white;
		border-radius: 10upx;

	}

	.click-item {
		width: 200upx;
		height: 200upx;
		border-radius: 50%;
		color: white;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	/* 新增相机界面样式 */
		.camera-container {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100vh;
			background-color: #000;
			z-index: 9999;
		}
		
		.camera-buttons {
			position: fixed;
			bottom: 50px;
			left: 0;
			width: 100%;
			display: flex;
			justify-content: space-around;
			padding: 0 20px;
		}
		
		.btn-capture {
			background-color: #007AFF;
			color: white;
			border-radius: 50px;
			padding: 10px 30px;
		}
		
		.btn-cancel {
			background-color: #FF3B30;
			color: white;
			border-radius: 50px;
			padding: 10px 30px;
		}
		
		/* 原有样式保持不变 */
		.fixed-bottom {
			position: fixed;
			width: 100%;
			padding: 20upx;
			bottom: 0;
			left: 0;
			z-index: 9999;
			background-color: white;
		}
		
		.cur {
			background-color: #0065B7 !important;
			color: white;
			border-radius: 10upx;
		}
		
		.click-item {
			width: 200upx;
			height: 200upx;
			border-radius: 50%;
			color: white;
			display: flex;
			justify-content: center;
			align-items: center;
		}
</style>